package org.i1510.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.bean.SessionUserBean;
import org.i1510.common.dao.ISysUserDao;
import org.i1510.common.po.SysUser;
import org.i1510.common.service.ISysUserService;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.KBProperties;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.encryption.Md5;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;






@Controller
@RequestMapping(value = "/admin")
public class SysUserController {
	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
	@Autowired
	private ISysUserService iSysUserService;
	@Autowired
	private ISysUserDao iSysUserDao;
	
	private ResultMapper mapper;
	/**
	*@Author Rambo
	*@Desc：注销
	*@param request
	*@param session
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-10-30 下午2:00:07 
	*/
	@RequestMapping(value = "/out", method = RequestMethod.GET)
	@ResponseBody
	public String out(HttpServletRequest request,HttpSession session,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			session.invalidate();
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("message", "注销成功!");
			
		}
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：登录控制
	*@param sysUser
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2013-11-21 下午5:38:15 
	*/
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public String login(HttpServletRequest request,HttpSession session,@ModelAttribute("validCode") String validCode,@ModelAttribute("name") String userName,@ModelAttribute("pwd") String userPw,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
//			Object obj = session.getAttribute(Captcha.NAME);
//			if(null != obj){
//				Captcha captcha = (Captcha) obj;				
//				if(captcha.isCorrect(validCode)){
					SysUser sysUser = iSysUserDao.findByPwAndName(Md5.getPassword(userPw), userName.toLowerCase().trim());
					if(null != sysUser){
						sysUser.setPw("");//不保存pw信息
						//创建用户session
						SessionUserBean sessionUserBean = new SessionUserBean();
						sessionUserBean.setSysUser(sysUser);
						sessionUserBean.setLoginTime(DateUtils.getNow());
					
						//session保存
						session.setAttribute("userSession", sessionUserBean);
						mapperRtn = ResultMapper.generateSuccess();
						//记录登录信息
					}else{
						mapperRtn = ResultMapper.generateFailure();
						mapperRtn.appendResult("message", "用户匹配错误!");										
					}
//				}else{
//					mapperRtn.appendResult("message", "验证码错误!");
//				}
//			}else{
//				mapperRtn.appendResult("message", "验证码失效!");
//			}
			
			
			
		}
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：保存对象
	*@param sysUser
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2013-11-15 下午4:20:56 
	*/
	@RequestMapping(value = "/sysUser/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,@Valid @ModelAttribute("sysUser") SysUser sysUser,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iSysUserService.save(sysUser,request);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：删除对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午3:38:17 
	*/
	@RequestMapping(value = "/sysUser/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iSysUserService.delete(docId);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：查看对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午3:39:35 
	*/
	@RequestMapping(value = "/sysUser/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			SysUser sysUser = iSysUserService.findById(docId);
			sysUser.setPw("");
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", sysUser);
		}		
		return mapperRtn.toJson();
	}
	@RequestMapping(value = "/sysUser/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@Valid @ModelAttribute("sysUser") SysUser sysUser,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			List  sysUsers = iSysUserService.getPage(sysUser, pageBean,conditions);
			int totalCount =  iSysUserService.getPageCount(sysUser,conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData",sysUsers);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：更新状态
	*@param request
	*@param docId
	*@param docStatus
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午4:41:35 
	*/
	@RequestMapping(value = "/sysUser/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				SysUser sysUser = new SysUser();
				
				sysUser.setDocId(docId);
				sysUser.setDocStatus(docStatus);
				mapper = iSysUserService.save(sysUser,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：重置密码
	*@param request
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午5:03:18 
	*/
	@RequestMapping(value = "/sysUser/rePw", method = RequestMethod.POST)
	@ResponseBody
	public String rePw(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				SysUser sysUser = new SysUser();
				sysUser.setDocId(docId);
				sysUser.setPw(Md5.getPassword(KBProperties.DEFAULTPASSWORD));
				mapper = iSysUserService.save(sysUser,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：修改密码
	*@param request
	*@param oldPw
	*@param newPw
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-5 下午2:45:45 
	*/
	@RequestMapping(value = "/sysUser/rePwMyself", method = RequestMethod.POST)
	@ResponseBody
	public String rePwMyself(HttpServletRequest request,@Valid @ModelAttribute("oldPw") String oldPw,@Valid @ModelAttribute("newPw") String newPw,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			SysUser sysUser = iSysUserDao.findByPwAndName(Md5.getPassword(oldPw), UserUtils.getSessionUserBean(request).getSysUser().getName().toLowerCase().trim());
			if(null != sysUser ){
				sysUser.setPw(Md5.getPassword(newPw));
				mapper = iSysUserService.save(sysUser,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "密码验证无法通过!");
			}
			
			
		}
		
		return mapper.toJson();
	}
	
}
